package com.djp.smartapp.dialog;

import android.app.AlertDialog;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.djp.smartapp.MainActivity;
import com.djp.smartapp.util.OkHttpUtil;
import com.google.gson.Gson;

public abstract class MyDialog{
    protected View view;
    protected MainActivity context;
    protected AlertDialog alertDialog;
    protected AlertDialog.Builder builder;
    protected Gson gson;
    protected OkHttpUtil okHttpUtil;


    protected MyDialog(MainActivity context) {
        this.context = context;
        init();
        initView(view);
    }

    //初始化数据
    private void init() {
        builder = new AlertDialog.Builder(this.context);
        LayoutInflater inflater = this.context.getLayoutInflater();
        view = inflater.inflate(setAlertLayout(), null, false);
        builder.setView(view);
        builder.setCancelable(false);
        alertDialog = builder.create();

        view.findViewById(setCancelButton()).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });

        view.findViewById(setFinishButton()).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setFinishButtonOnClick();
            }
        });
        gson = new Gson();
        okHttpUtil = OkHttpUtil.getOkHttpUtil();
    }

    //返回dialog对应的布局文件id
    protected abstract int setAlertLayout();

    //设置取消按钮
    protected abstract int setCancelButton();

    //设置确认按钮
    protected abstract int setFinishButton();

    //设置确认按钮的点击事件
    protected abstract void setFinishButtonOnClick();

    //初始化dialog中的控件
    protected abstract void initView(View view);

   //显示dialog
    public void show(){
        alertDialog.show();
        WindowManager windowManager = context.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = alertDialog.getWindow().getAttributes();
        lp.width = (int)(display.getWidth()); //设置宽度
        alertDialog.getWindow().setAttributes(lp);
    };

    //关闭dialog
    public void dismiss(){
        alertDialog.dismiss();
    }

    //显示一个toast
    protected void toast(String msg){
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }
}
